"""
模块注释
"""
from urllib import request
import re


class Spider():
    """
    类注释
    """
    url = 'https://egame.qq.com/livelist?layoutid=lol'
    root_pattern = '<li class="gui-list-normal gui-list-percent" data-v-\w*?>([\s\S]*?)</li>'
    live_name_pattern = '<h4 class="info-livename">([\s\S]*?)</h4>'
    anchor_name_pattern = '<p class="name">([\S]*?)</p>'
    anchor_popular_pattern = '<span class="popular"><img src=".*?">([\s\S]*?)</span>'

    def __fetch_content(self):
        """
        获取html文本
        """
        # 代码注释
        r = request.urlopen(Spider.url)

        # 代码注释
        html = str(r.read(), encoding='utf-8')
        return html

    def __analysis(self, html):
        """ 
        分析文本，提取数据 
        """
        root_html = re.findall(Spider.root_pattern, html)

        live_rooms = []
        for html in root_html:
            live_name = re.findall(Spider.live_name_pattern, html)
            anchor_name = re.findall(Spider.anchor_name_pattern, html)
            anchor_popular = re.findall(Spider.anchor_popular_pattern, html)
            live_room = {
                'live_name': live_name[0],
                'anchor_name': anchor_name[0],
                'anchor_popular': anchor_popular[0]
            }
            live_rooms.append(live_room)

        return live_rooms

    def __refine(self, live_rooms):
        """ 
        数据精炼 
        """
        return map(
            lambda live_room: {
                'live_name': live_room['live_name'].strip(),
                'anchor_name': live_room['anchor_name'].strip(),
                'anchor_popular': live_room['anchor_popular'].strip(),
            },
            live_rooms
        )

    def __sort_seed(self, live_room):
        """ 
        种子
        """
        result = re.findall('\d*', live_room['anchor_popular'])
        number = float(result[0])
        if '万' in live_room['anchor_popular']:
            number *= 1000
        return number

    def __sort(self, live_rooms):
        """ 
        排序 
        """
        return sorted(live_rooms, key=self.__sort_seed, reverse=True)

    def __show(self, live_rooms):
        """ 
        打印展示 
        """
        for rank in range(0, len(live_rooms)):
            print('排名：'+str(rank+1),
                  '人气：'+live_rooms[rank]['anchor_popular'],
                  '直播间名称：'+live_rooms[rank]['live_name'],
                  '主播姓名：'+live_rooms[rank]['anchor_name'])
        # for live_room in live_rooms:
        #     print('人气：'+live_room['anchor_popular'],
        #           '直播间名称：'+live_room['live_name'],
        #           '主播姓名：'+live_room['anchor_name'])

    def go(self):
        html = self.__fetch_content()
        live_rooms = self.__analysis(html)
        live_rooms = list(self.__refine(live_rooms))
        live_rooms = self.__sort(live_rooms)
        self.__show(live_rooms)


spider = Spider()
spider.go()
